package com.net.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
public class RequestUtil {
	
	private static final int TIME_OUT = 10000;
	public static Response sendRequestByPayload(Map<String, String> headers, Map<String, String> cookies, Map<String, String> payloadData, String url, String method, int timeout){
		String payload = MapToJson(payloadData);
		Response res = null;
		try {
			Connection connection = Jsoup.connect(url);
			if(headers != null){
				connection = connection.headers(headers);
			}
			
			if(cookies != null){
				connection = connection.cookies(cookies);
			}
			
			if(payload != null){
				connection = connection.requestBody(payload);
			}
			
			if(timeout == 0 || timeout < 0){
				connection.timeout(TIME_OUT);
			}else{
				connection.timeout(timeout);
			}
			res = connection.ignoreContentType(true).timeout(TIME_OUT).method(Method.valueOf(method)).execute();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return res;
	}
	
	
	public static String MapToJson(Map map){
		JSONObject jsonObject = null;
        try{
        	jsonObject = JSONObject.fromObject(map);  
        }catch(JSONException e){
        	return null;
        }
        
        if(jsonObject == null ){
        	return null;
        }
        
        String result = jsonObject.toString();  
		return result;
	}
	
	public static Map<String, Object> jsonToMap(String jsonStr){
		Map<String,Object> map =  JSONUtils.getProperties(JSONObject.fromObject(jsonStr));
		for (String key : map.keySet()) {   
		System.out.println(key+":"+map.get(key));   
		} 
		
		return map;
	}
	
    public static HashMap<String, Object> jsonToHashMap(Object object)
    {
    HashMap<String, Object> data = new HashMap<String, Object>();
    // 将json字符串转换成jsonObject
    JSONObject jsonObject = JSONObject.fromObject(object);
    Iterator it = jsonObject.keys();
    // 遍历jsonObject数据，添加到Map对象
    while (it.hasNext())
    {
    String key = String.valueOf(it.next());
    Object value = jsonObject.get(key);
    data.put(key, value);
    }
    return data;
    }
}
